<template>
  <div class="ssal-calendar-container">
    <div class="multiple-week">
      <div v-for="(item, index) in multipleweek" :key="item.id" class="multiple-week-box">
        <div class="multiple-cell" v-for="(cell, idx) in item" :key="cell.date" :data-date="cell.date">
          <div class="multiple-container">
            <div :class="['title-header', cell.isDay ? 'today' : '', cell.weekend ? 'weekday' : '']">
              <span class="center-title">{{cell.lunar.ncWeek}}</span>
              <span class="title-date"><span>{{cell.date}}</span></span>
            </div>
            <div class="multiple-list" v-if="dayEvents[index] && dayEvents[index].length > 0">
              <ScrollBar
                autoHide
                :forData="dayEvents[index].length"
                :ScrollTop="0"
                :listenScrollBottom="listenScrollBottom"
                :listenScrollTop="listenScrollTop"
                :listenScroll="listenEventScroll"
              >
                <div>
                  <div 
                    v-for="(list, ldx) in dayEvents[index][idx]" 
                    :key="list.id" 
                    class="multiple-event-cell" 
                    data-type="multipleEvent" 
                    :data-day="idx" 
                    :data-multipleRow="index" 
                    @click="getEvent($event, list)"
                    @mouseover="itemOver($event)"
                    :style="{color: list.color}"
                  >
                    <el-tag size="small" style="margin-right:5px"  @click.stop.prevent="jumpModel($event, ldx)" v-if="list.relateItems && list.relateItems.length > 0">
                      {{ (list.relateItems && list.relateItems.length > 0) ? list.relateItems[0].label : '' }}
                    </el-tag>
                    <span v-if="list.codeName" style="font-size:12px;display:inline-block;margin-top: 2px;">{{ list.codeName }}·</span>
                    <el-popover
                      :width="270"
                      trigger="hover"
                      :placement="placement"
                      popper-class="event-detail-pop"
                    >
                      <template #reference>
                        <div 
                          :class="['multiple-event-data', list.complete ? 'event-complete' : '']" 
                          data-type="multipleEvent" 
                          :data-day="idx" 
                          :data-multipleRow="index"
                          :style="{textDecoration: list.state == 2 ? 'line-through' : '' }"
                        >
                          <pennant 
                            v-if="Number(list.targetType) === 1 || Number(list.targetType) === 0"
                            style="margin-left:3px"
                            theme="filled" 
                            size="13" 
                            :fill="list.color"
                          />
                          <template v-if="list.state == -1">
                            <file-date-one style="top: 3px;position: relative;" theme="outline" size="12" :fill="list.color" />
                            (待审核)
                          </template>
                          <template v-else-if="list.state == -2">
                            <close-one style="top: 2px;position: relative;" theme="outline" size="13" :fill="list.color" />
                            (已驳回)
                          </template>
                          <template v-else-if="list.state == 3">
                            <file-withdrawal style="top: 2px;position: relative;" theme="outline" size="12" :fill="list.color" />
                            (已退回)
                          </template>
                          {{list.title}}
                        </div>
                      </template>
                      <div class="event-detail">
                        <el-row align="middle" justify="start" style="border-bottom: 1px solid #f0f0f0;padding-bottom: 5px;">
                          <el-button
                              size="small"
                              type="primary"
                              link
                              :icon="View"
                              @click="readInfo(list)"
                              >查看</el-button
                          >
                          <el-button 
                            v-if="list.state == 0 && list.sponsor.userId == userId"
                            size="small" 
                            type="primary" 
                            link 
                            @click="editInfo(list)"
                          >
                            <edit-two theme="outline" size="14" style="margin-right:5px;margin-top:2px" />
                            编辑
                          </el-button>
                          <el-button 
                            v-if="list.state == 0 || list.state == 1"
                            size="small" 
                            type="primary" 
                            link 
                            @click="completeEvent(list, index, idx, ldx)" 
                            style="margin-left:0;margin-top:1px"
                          >
                            <done-all theme="outline" size="16" style="margin-right:5px"/>
                            完成
                          </el-button>
                          <el-button 
                            v-if="
                              list.state == -2 || 
                              (list.state == 0 && list.sponsor.id == userId) || 
                              (list.state == 1 && list.sponsor.id == userId) ||
                              list.state == 2 || list.state == 3 || list.state == 4 || list.state == 5
                            "
                            size="small" 
                            type="danger" 
                            link 
                            style="margin-left:0" 
                            @click="delEvent(list)"
                          >
                            <delete theme="outline" size="14" style="margin-right:5px;margin-top:2px" />
                            删除
                          </el-button>
                          <el-button 
                            v-if="list.state == -1 && list.approverIds.includes(userId)"
                            size="small"
                            type="primary"
                            link
                            style="margin-left: 0; margin-top: 2px"
                            @click="approverAccess(list)"
                          >
                            <el-icon><Check /></el-icon>
                            通过
                          </el-button>
                          <el-button 
                            v-if="list.state == -1 && list.approverIds.includes(userId)"
                            size="small"
                            type="danger"
                            link
                            style="margin-left: 0; margin-top: 2px"
                            @click="approverReject(list)"
                          >
                            <close theme="outline" size="14" style="margin-right: 5px; margin-top: 1px" />
                            拒绝
                          </el-button>
                        </el-row>
                        <el-row justify="start" style="margin: 10px 0;flex-wrap: nowrap;">
                          <round 
                            style="margin: 0 6px 0 2px"
                            theme="filled" 
                            size="8" 
                            fill="#18a058" 
                          />
                          <div class="event-detail-data">{{ list.title }}</div>
                        </el-row>
                        <el-row justify="start" style="margin-bottom: 10px;flex-wrap: nowrap;">
                          <calendar-dot theme="outline" size="14" />
                          <div class="event-detail-data">{{ formatDurationTime(list) }}</div>
                        </el-row>
                        <el-row style="margin-top:5px;flex-wrap: nowrap;" justify="start">
                          <user theme="outline" size="14" />
                          <div class="event-detail-data">{{ (item.relateItems && item.relateItems.length > 0) ? item.relateItems[0].label : '-'}}</div>
                        </el-row>
                        <el-row justify="start" style="margin-top: 5px;flex-wrap: nowrap;">
                          <el-icon style="margin-right: 8px;margin-top: 4px;" color="#18a058"><CollectionTag /></el-icon>
                          <el-tag size="small" class="showAllTag">{{ list.codeName }}</el-tag>
                        </el-row>
                      </div>
                    </el-popover>
                  </div>
                  <template v-if="dayEvents[index][idx].length < 5">
                    <div v-for="list in 5 - dayEvents[index][idx].length" :key="list" :data-index="list" class="multiple-event-cell" @click="addEvent(list, cell, index, dayEvents[index][idx].length)">
                      <div class="multiple-event-data"></div>
                    </div>
                  </template>
                </div>
              </ScrollBar>
            </div>
            <div class="multiple-list" v-else>
              <ScrollBar
                autoHide
                :forData="6"
                :ScrollTop="0"
                :listenScrollBottom="listenScrollBottom"
                :listenScrollTop="listenScrollTop"
                :listenScroll="listenScroll"
              >
                <div>
                  <div v-for="list in 5" :key="list" class="multiple-event-cell" @click="addEvent(list, cell, index, 0)">
                    <div class="multiple-event-data"></div>
                  </div>
                </div>
              </ScrollBar>
            </div>
          </div>
        </div>
        <div class="multiple-cell">
          <div class="multiple-container">
            <div class="title-header">
              <span class="center-title">总结</span>
            </div>
            <div class="multiple-list multiple-summary" @click="addSummary(index)">
              <div class="no-black" v-if="!daySummary[index]">
                <i class="fa fa-cubes"></i>
                <span class="add-tips">添加总结</span>
              </div>
              <div v-else v-html="daySummary[index]" class="multiple-summary-data"></div>
            </div>
          </div>
        </div>
      </div>
      <div v-if="showTime" class="time-placeholder-box time-month-placeholder-box" >
        <div class="close-bg" @click="showTime = false"></div>
        <div class="time-placeholder timeRef" :style="{ top: timeDistance.top, left: timeDistance.left, width: 'calc(100% / 7)', marginLeft: 0}" id="timeRef" >
          添加事件
        </div>
      </div>
    </div>
    <EventDetail
      :dialogEventDetailVisible="dialogEventDetailVisible"
      :event="itemInfo"
      @edit-info="editInfo"
      @del-event="delEvent"
    ></EventDetail>
    <EventForm
      :dialogEventFormVisible="dialogEventFormVisible"
      :code="formCode"
      :item-id="itemId"
      :title="formTitle"
      :event-id="eventId"
      :readOnly="readOnly"
    ></EventForm>
    <model-option-box
      :dialogModelVisible="dialogModelVisible"
      :type="modelType"
      :valueData="evDataList"
      @close-form="CloseModel"
      @get-quick="getQuick"
    ></model-option-box>
    <summary-form v-model:dialogDrawer="dialogSummary" v-model:defaultForm="defaultForm" @onSubmit="onSummary"></summary-form>
  </div>
</template>

<script>
import { toRefs, onMounted, ref, reactive, nextTick, watch, computed, getCurrentInstance } from 'vue'
import { CalendarDot, User, EditTwo, DoneAll, Delete, Round, Pennant, FileDateOne, CloseOne, FileWithdrawal, Close } from '@icon-park/vue-next'
import { CollectionTag, Check, View } from '@element-plus/icons-vue'
import { getAnyTimeEvent } from '../lib/event.js'
import { formatShortTime } from '../lib/utils.js'
import { currentForm } from "../lib/config.js";
import ScrollBar from "../ScrollBar/index.vue";
import EventDetail from "../EventDetail/index.vue";
import EventForm from "../EventForm/index.vue";
import SummaryForm from "../SummaryForm/index.vue";
import ModelOptionBox from "../ModelOptionBox/index.vue";

import Cookies from 'js-cookie'
import { ElMessage } from 'element-plus'

export default {
    name: 'MultipleWeek',
    components: {
      ScrollBar,
      EventDetail,
      EventForm,
      CalendarDot,
      User,
      EditTwo,
      DoneAll, 
      Delete,
      SummaryForm,
      ModelOptionBox,
      Round,
      CollectionTag,
      Pennant,
      FileDateOne,
      CloseOne,
      FileWithdrawal,
      Check,
      Close
    },
    props: {
      weekTitle: {
        type: Array,
        default() {
          return []
        }
      },
      multipleweek: {
        type: Array,
        default() {
          return []
        }
      },
      events: {
        type: Array,
        default() {
          return []
        }
      },
      belongsUser: {
        type: Array,
        default() {
          return []
        }
      },
      evDataList: {
        type: Array,
        default() {
          return []
        }
      }
    },
    emits: ['addSummary', 'delEvent'],
    setup(props, context) {
      const { events, multipleweek } = toRefs(props)
      const userId = Cookies.get('userId')
      const state = reactive({
        dayEvents: [[],[]],
        itemInfo: {},
        defaultForm: {},
        dialogEventFormVisible: false,
        dialogEventDetailVisible: false,
        showTime: false,
        timeDistance: {
          top: 0,
          left: 0,
        },
        placement: 'bottom-end',
        dialogSummary: false,
        daySummary: [],
        dayIndex: null,
        dialogModelVisible: false,
        modelType: 1,
        
        formCode: null,
        itemId: null,
        formTitle: null,
        // 当前存在的事项
        formExist: currentForm,
        eventId: null, // 事件的id
        readOnly: false
      })
      let num = 0;
      const getMultipleWeekEvent = () => {
        let arr = []
        for(let i = 0; i < multipleweek.value.length; i ++) {
          arr.push([])
          for(let j = 0; j < multipleweek.value[i].length; j ++){
            let item = multipleweek.value[i][j]
            const item_event = getAnyTimeEvent(item.fullDate + ' 00:00:00', events.value)
            arr[i].push(item_event)
          }
        }
        return arr
      }
      let eleHeight = ref(0)
      watch(
        () => events.value,
        () => {
          state.dayEvents = getMultipleWeekEvent();
        },
        {
          deep: true
        }
      )
      watch(
        () => multipleweek.value,
        () => {
          state.dayEvents = getMultipleWeekEvent();
        },
        {
          deep: true
        }
      )
       // 格式化时间
      const formatDurationTime = computed(() => {
        return item => {
          if(!item.actionStartTime) return ''
          return formatShortTime(item)
        }
      })
      onMounted(() => {
        nextTick(() => {
          if(document.getElementsByClassName('multiple-container')) {
            eleHeight.value = document.getElementsByClassName('multiple-container')[0].offsetHeight || 140
            window.addEventListener('resize',() => {
              eleHeight.value = document.getElementsByClassName('multiple-container')[0].offsetHeight || 140
            })
          }
          state.dayEvents = getMultipleWeekEvent()
        })
      })
      const listenScrollBottom = () => {};
      const listenScrollTop = () => {};
      const listenScroll = () => {}
      const listenEventScroll = () => {}
      const addSummary = (index) => {
        state.dayIndex = index
        state.defaultForm['content'] = state.daySummary[index]
        state.dialogSummary = true
      }
      // 添加事件
      const addEvent = (index, e, rowIndex, eventLength) => {
        num++;
        setTimeout(() => {
          if (num == 1) {
            // const { fullDate } = e
            // state.defaultForm["startTime"] = fullDate + ` ${timeStr(((index - 1) * 4).toFixed(1))}`
            // state.defaultForm["endTime"] = fullDate + ` ${timeStr((index * 4).toFixed(1))}`
            // state.defaultForm["isAllDay"] = false
            // state.defaultForm['center'] = true
            // state.dialogEventFormVisible = !state.dialogEventFormVisible
            state.showTime = true
            state.modelType = 1
            eventDistance(e, rowIndex, index, eventLength)
          }
          if (num == 2) {
            state.showTime = true
            state.modelType = 2
            eventDistance(e, rowIndex, index, eventLength)
            console.log("双击");
          }
          if (num > 2) {
            num = 0;
          }
          num = 0;
          timeStr(((index - 1) * 4).toFixed(1)) // 开始时间
          timeStr((index * 4).toFixed(1)) // 结束时间

        }, 250);
      }
      // 点击的时候的拼接的时间段
      const timeStr = (time) => {
        const times = String(time).split('.')
        const hour = times[0] < 10 ? '0' + times[0] : times[0]
        const min = (times[1] / 10 * 60 == 0 && hour == 24) ? 59 : times[1] / 10 * 60
        return (hour == 24 ? 23 : hour) + ':' + (min < 10 ? '0' + min : min)
      }
      const eventDistance = (e, rowIndex, index, eventLength) => {
        // 25% 不是均分的
        const dayIndex = e.day == 0 ? 7 : e.day
        const topRow = rowIndex == 1 ? 2 : rowIndex
        const topDay = dayIndex < 5 ? 0 : 1
        const leftDay = dayIndex < 5 ? dayIndex - 1 : (dayIndex - 5)
        const lineIndex = eventLength + index
        state.timeDistance.top = `calc((100% / 4 * ${topRow + topDay} + ${50 - (topRow + topDay) * 2}px + ${(lineIndex - 1) * 27 + 2 * (lineIndex - 1)}px)`;
        state.timeDistance.left = `calc((100% / 4) * ${leftDay} + ${20 - leftDay * 2}px)`
        state.dialogModelVisible = !state.dialogModelVisible;
      }
      const getEvent = (e, info) => {
        if(!e.target.dataset.day) return 
        state.itemInfo = {
          ele: e,
          info
        }
        // state.dialogEventDetailVisible = !state.dialogEventDetailVisible
      }
      const editInfo = (e) => {
        // let obj = {}
        // for(let key in e) {
        //   obj[key] = e[key]
        // }
        // state.defaultForm = obj
        state.eventId = e.id
        state.formCode = e.code
        state.formTitle = e.codeName
        const isExist = state.formExist.find(item => item == e.code)
        if(!isExist) {
          ElMessage.error(`${e.codeName}\n编辑操作不存在`)
          return
        }
        state.dialogEventFormVisible = !state.dialogEventFormVisible
      }
      // 删除form
      const delEvent = (e) => {
        context.emit('delEvent', e)
        // state.dialogEventDetailVisible = !state.dialogEventDetailVisible
      }
      // 关闭Form
      const CloseForm = () => {
        state.showHeaderTime = false;
        state.showTime = false;
        state.defaultForm = {};
      }
      // 获取form
      const getForm = (e) => {
        context.emit('submitForm', e)
      }
      // 事件完成状态
      const eventStatusChange = (e, index, idx, ldx) => {
        state.dayEvents[index][idx][ldx].complete = e
      }
      // 模块跳转
      const jumpModel = (e, index) => {
        console.log(e, index)
      }
      // 完成事件
      const completeEvent = (e, index, idx, ldx) => {
        // state.dayEvents[index][idx][ldx].complete = true
        context.emit('completeEvent', e)
      }
      // 鼠标滑过
      const itemOver = e => {
        const windowY = document.body.clientHeight
        if(windowY - e.screenY < 280) {
          state.placement = 'top-start'
        }else{
          state.placement = 'bottom-end'
        }
      }
      // 提交总结
      const onSummary = e => {
        // const lastDay = multipleweek.value[state.dayIndex][multipleweek.value[state.dayIndex].length - 1]
        // state.daySummary[state.dayIndex] = e.content
        context.emit('addSummary', lastDay)
      }
      // 关闭model
      const CloseModel = () => {
        // showHeaderTime.value = false;
        state.showTime = false;
      };
      const getQuick = (e) => {
         // 判断是否存在code
        const isExist = state.formExist.find(item => item == e.code)
        if(!isExist) {
          ElMessage.error(`${e.name}\n创建操作不存在`)
          return
        }
        state.formCode = e.code
        state.itemId = e.id
        state.formTitle = e.name
        state.eventId = null
        setTimeout(() => {
          context.emit("update:scrollDisabled", true);
        }, 300);
        state.dialogEventFormVisible = !state.dialogEventFormVisible
      };
      // 审批通过
      const approverAccess = e => {
        context.emit('approverAccess', e)
      }
      // 审批拒绝
      const approverReject = e => {
        context.emit('approverReject', e)
      }
      
      // 查看事项
      const readInfo = (e) => {
        state.eventId = e.id
        state.formCode = e.code
        state.formTitle = e.codeName
        state.readOnly = true
        const isExist = state.formExist.find(item => item == e.code)
        if(!isExist) {
          ElMessage.error(`${e.codeName}\n查看操作不存在`)
          return
        }
        context.emit("update:scrollDisabled", true);
        state.dialogEventFormVisible = !state.dialogEventFormVisible
      }
      return {
        ...toRefs(state),
        eleHeight,
        listenScrollBottom,
        listenScrollTop,
        listenScroll,
        listenEventScroll,
        addSummary,
        addEvent,
        getEvent,
        editInfo,
        delEvent,
        CloseForm,
        getForm,
        eventStatusChange,
        jumpModel,
        completeEvent,
        itemOver,
        onSummary,
        CloseModel,
        getQuick,
        formatDurationTime,
        userId,
        approverAccess,
        approverReject,
        View,
        readInfo
      }
    }
}
</script>

<style scoped lang="scss">
.ssal-calendar-container{
  height: calc(100% - 41px);
  position: relative;
  .multiple-week{
    padding: 10px 10px 0;
    position: relative;
    height: 100%;
    display: flex;
    flex-direction: column;
    justify-content: center;
    border: 1px solid var(--ss-color-border);
    &::after{
      content: "";
      position: absolute;
      top: 0;
      bottom: 0;
      left: 0;
      right: 0;
      background: var(--el-color-primary-light-9);
      opacity: .5;
      filter: blur(5px);
    }
    .multiple-week-box{
      position: relative;
      z-index: 2;
      display: flex;
      flex-wrap: wrap;
      justify-content: space-between;
      height: 50%;
      .multiple-cell{
        width: calc(25% - 10px);
        background: #fff;
        margin: 0 10px 12px 0;
        height: calc(100% / 2 - 12px);
        border-radius: 2px;
        transition: .2s;
        position: relative;
        &:nth-child(4n + 4){
          margin-right: 0;
        }
        &:hover{
          box-shadow: rgba(0, 0, 0, 0.08) 0px 4px 12px;
        }
        .multiple-event-dotted{
          width: 5px;
          height: 5px;
          border-radius: 50%;
          margin: 8px 10px 0 0;
        }
        .multiple-container{
          padding: 8px 10px;
          height: 100%;
          .title-header{
            display: flex;
            justify-content: space-between;
            align-items: center;
            .center-title{
              font-size: 14px;
              color: var(--ss-color-text-black);
              font-weight: bold;
            }
            .title-date{
              span{
                position: relative;
                z-index: 1;
              }
            }
          }
          .weekday{
            .center-title{
              // color: #f56c6c;
            }
            .title-date{
              // color: #f56c6c;
            }
          }
          .today {
            .center-title{
              color: var(--ss-color-primary);
              border-radius: 2px;
            }
            .title-date{
              position: relative;
              color: var(--ss-color-white);
              &::after{
                content: "";
                position: absolute;
                width: 24px;
                height: 24px;
                border-radius: 50%;
                background: var(--ss-color-primary);
                right: -5px;
                top: 0;
                bottom: 0;
                margin: auto;
              }
            }
          }
        }
        .more-model{
          position: absolute;
          top: 0;
          right: 0;
          left: 0;
          bottom: 0;
          padding: 10px;
          background: var(--ss-color-white);
        }
      }
    }
    .multiple-list{
      margin-top: 6px;
      overflow: auto;
      height: 85%;
      position: relative;
      .multiple-event-cell{
        padding: 5px 0 0;
        display: flex;
        align-items: flex-start;
        margin-bottom: 2px; 
        cursor: pointer;
        font-size: 12px;
        .multiple-event-tag{
          background: var(--el-color-primary-light-9);
          color: var(--ss-color-primary);
          border-radius: 2px;
          padding: 2px 6px;
          font-size: 12px;
          margin-right: 5px;
        }
        .multiple-event-data{
          border-bottom: 1px solid var(--el-color-primary-light-9);
          flex: 1;
          overflow: hidden;
          padding-bottom: 2px;
          font-size: 12px;
          padding-top: 2px;
          text-overflow: ellipsis;
          white-space: nowrap;
          min-height: 22px;
        }
        .event-complete{
          text-decoration: line-through;
        }
      }
      .multiple-more{
        display: flex;
        justify-content: center;
        align-items: center;
        padding: 6px 0;
        font-size: 12px;
        color: var(--ss-color-gery);
        cursor: pointer;
      }
    }
    .multiple-summary{
      position: relative;
      &::after{
        transition: .2s;
        cursor: pointer;
      }
      .no-black{
        height: 100%;
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        color: var(--el-color-primary-light-5);
        &:hover{
          cursor: pointer;
          &::after{
            content: "+";
            position: absolute;
            top: 0;
            bottom: 0;
            left: 0;
            right: 0;
            font-size: 100px;
            color: var(--el-color-primary-light-8);
            display: flex;
            justify-content: center;
            align-items: center;
            transition: .2s;
            background: var(--ss-color-white);
          }
        }
        .fa{
          font-size: 45px;
        }
        .add-tips{
          margin-top: 10px;
        }
      }
      .multiple-summary-data{
        :deep(img) {
          max-width: 100%;
        }
      }
    }
  }
  .time-placeholder {
    position: absolute;
    z-index: 999;
    margin-left: 80px;
    background: #ecf5ff;
    border: 1px dashed var(--ss-color-primary);
    font-size: 12px;
    text-align: center;
    color: var(--ss-color-primary);
    height: 20px;
    box-sizing: border-box;
    line-height: 20px;
  }
  .close-bg {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    z-index: 998;
    background: rgba(0, 0, 0, 0.2);
  }
  .time-month-placeholder-box {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
  }
}
:deep(.el-tag--small){
  .el-tag__content{
    max-width: 76px;
    overflow:hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  }
}
:deep(.showAllTag){
    .el-tag__content {
        max-width: unset;
    }
}
:deep(.el-button--small [class*=el-icon]+span){
  margin-left: 0;
}
</style>
<style lang="scss">
.event-detail-pop{
  padding-bottom: 6px !important;
  .el-popover__title{
    font-size: 14px;
    padding-bottom: 8px;
    border-bottom: 1px solid var(--el-color-primary-light-9);
  }
  .event-detail {
    font-size: 12px;
    color: var(--el-color-primary);
    .event-detail-data{
      margin-left: 5px;
      color: var(--el-text-color-regular);
    }
  }
}
</style>